from rest_framework import status
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.http import Http404
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token


from .models import Article
from .serializers import ArticleSerializer, UserSerializer


@api_view(['POST'])
def login_view(request):
    username = request.data.get('username')
    password = request.data.get('password')

    user = authenticate(username=username, password=password)
    print("-----------")
    if not user:
        return Response({"error": "Invaild Credentials"}, status=400)
    token, _ = Token.objects.get_or_create(user=user)
    return Response({
        'token': token.key,
        'username': user.username,
    }, status=200)


@api_view(['GET'])
def user_info(request):
    token_string = request.GET.get('token')

    if not token_string:
        return Response({"error": "Token 参数缺失"}, status=400)
    try:
        token = Token.objects.get(key=token_string)
        serializer = UserSerializer(token.user)
        return Response(serializer.data)
    except Token.DoesNotExist:
        return Response({"error": "无效的 Token"}, status=401)


class ArticleList(APIView):
    # def get(self,request,format=None):
    #     articles=Article.objects.get()
    #     serializer=ArticleSerializer(articles,many=True)
    # return Response(serializer.data)

    def get(self, request, format=None):
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = ArticleSerializer(
            data=request.data,
            context={'request': request}
        )
        if serializer.is_valid():
            serializer.save(author=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ArticleDetail(APIView):
    def get_object(self, pk):
        try:
            return Article.objects.get(pk=pk)
        except Article.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        article = self.get_object(pk)
        serializer = ArticleSerializer(article)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        article = self.get_object(pk)
        serializer = ArticleSerializer(instance=article, data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        article = self.get_object(pk)
        article.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

